<?php
declare (strict_types=1);

namespace app\api\controller;


use app\model\CommentModel;
use think\facade\Request;
use think\facade\Validate;
use think\facade\View;

class Comment
{
    public function add()
    {
        $param = Request::param();

        $validate = Validate::rule([
            'comment_content|评论内容' => 'require|min:1|max:500',
            'email|邮箱' => 'require|min:3|max:100',
            'nickname|用户昵称' => 'require|min:1|max:20',
            'article_id|文章id' => 'require|between:1,'.PHP_INT_MAX,
        ]);

        if(!$validate->check($param)){
            $data = [
                'status' => 0,
                'message' => $validate->getError(),
                'data' => []
            ];
            return json($data);
        }

        $param['add_time'] = time();
        $param['update_time'] = time();
        $result = CommentModel::create($param);

        $data = [
            'status' => 12,
            'message' => '',
            'data' => [
                'result' => $result,
            ],
        ];
        return json($data);
    }

    public function list()
    {
        $article_id = Request::param('article_id');
        $validate = Validate::rule([
            'article_id|文章id' => 'require|between:1,'.PHP_INT_MAX,
        ]);

        if(!$validate->check(['article_id' => $article_id])){
            $data = [
                'status' => 0,
                'message' => $validate->getError(),
                'data' => []
            ];
            return json($data);
        }

        $commentList = CommentModel::order('add_time','desc')->where('article_id','=',$article_id)->select();

        $commentData = [];
        foreach ($commentList as $row) {
            $commentData[] = [
                'comment_id' => $row['comment_id'],
                'comment_content' => $row['comment_content'],
                'email' => $row['email'],
                'nickname' => $row['nickname'],
                'add_time' => date("Y-m-d H:i:s",$row['add_time']),
                'update_time' => $row['update_time'],
            ];
        }
        $data = [
            'status' => 12,
            'message' => '',
            'data' => [
                'commentData' => $commentData,
            ],
        ];

        return json($data);
    }
}